<template>
  <div>
    <el-dialog v-model="visible" width="45vw">
      <template #header>
        <el-space>
          <span style="margin-right: 20px">JSON</span>
          <el-switch v-model="tidMode" active-text="tid模式" inactive-text="默认" @change="onModeChange" />
          <el-switch v-model="beautify" active-text="美化" inactive-text="压缩" @change="onModeChange" />
        </el-space>
      </template>

      <el-input
        v-loading="loading"
        v-model="jsonOut"
        type="textarea"
        :autosize="{ minRows: 10, maxRows: 20 }"
        style="width: 100%"
      />

      <template #footer>
        <el-button v-copy="jsonOut" type="warning"> 复制JSON </el-button>
        <el-button type="primary" @click="hideModal"> 关闭 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JsonPreview">
import { ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
  template: {
    type: Object,
    default: () => ({})
  }
});

const visible = ref(false);
const loading = ref(true);
const jsonOut = ref('');
const tidMode = ref(false);
const beautify = ref(false);

const hideModal = () => {
  visible.value = false;
};

const show = () => {
  visible.value = true;
  loading.value = true;
  nextTick(() => {
    setTimeout(() => {
      try {
        const json = tidMode.value ? props.template.getJsonTid() : props.template.getJson();
        const pretty = beautify.value ? 2 : 0;
        jsonOut.value = JSON.stringify(json, null, pretty);
      } catch (e) {
        ElMessage.error('解析失败');
        jsonOut.value = '';
      } finally {
        loading.value = false;
      }
    }, 300);
  });
};

const onModeChange = () => {
  show();
};

defineExpose({
  show
});
</script>
